package com.pxmeta.common.utils;

 
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
 
public class SignUtil {
    public static String APP_ID="wx49d11b54fab83222";//在controller中初始化
    public static String APP_SECRET="638db4eb86f71d4aa45a56eda0435b46";
 
    public static Map<String, String> getResult(String url){
 
        Map<String, String> ret = sign(getTicket(), url);
        ret.put("appId", getAppId());
        return ret;
    }
 
    private static String getAppId(){
        return APP_ID;
    }
 
    private static String getToken(){
        String accessToken = "";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+getAppId()+"&secret="+APP_SECRET;
        try {
            String resultString = HttpUtil.get(url);
            if (null != resultString && !"".equals(resultString)) {
                System.out.println(resultString);
                JSONObject json = JSONObject.parseObject(resultString);
                accessToken = json.getString("access_token");
 
            }else{
                System.out.println("返回值为空，请检查请求报文或者请求地址是否正确");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
 
    private static String getTicket(){
 
        String ticket = "";
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getToken()+"&type=jsapi";
 
        try {
            String resultString =HttpUtil.get(url);
            if (null != resultString && !"".equals(resultString)) {
                System.out.println(resultString);
                JSONObject json = JSONObject.parseObject(resultString);
                ticket = json.getString("ticket");
            }else{
                System.out.println("返回值为空，请检查请求报文或者请求地址是否正确");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }
 
    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
 
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);
 
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
 
        return ret;
    }
 
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
 
    private static String create_nonce_str() {
        return UUID.randomUUID().toString().replace("-","");
    }
 
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}